package com.sh.rbac.domain.entity;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 登录用户详情实体类
 *
 * @author lucky
 * @since 2024-04-07 14:20
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {

    @Schema(description = "用户信息")
    private User user;

    //@Schema(description = "用户角色")
    //private Set<String> roles;

    @Schema(description = "用户权限")
    private Set<String> permissions;

    private List<SimpleGrantedAuthority> authorities;


    // 用户权限集合
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 判断授权信息是否为空
        if (authorities == null) {
            return new ArrayList<>();
        }

        // 用户角色
        //roles.forEach(role ->
        //        authorities.add(new SimpleGrantedAuthority(role))
        //);

        // 过滤掉 null 和空字符串
        List<String> filteredPermissions = new ArrayList<>();
        for (String s : permissions) {
            if (s != null && !s.trim().isEmpty()) {
                filteredPermissions.add(s);
            }
        }

        // 将权限名称添加到授权信息列表中
        filteredPermissions.forEach(permission ->
                authorities.add(new SimpleGrantedAuthority(permission))
        );

        // 返回授权信息列表
        return authorities;

    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    // 用户是否过期 true: 未过期, false: 已过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 用户是否被锁定 true: 未锁定, false: 已锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 用户密码是否过期 true: 未过期, false: 已过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 用户是否可用 true: 可用, false: 不可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
